// pages/workTaskDetail/workTaskDetail.js

const app = getApp()
const lbbService = require('../service/service.js');
const util = require('../../utils/util.js');
const { fromJSON } = require('../../utils/weichatPb/src/enum.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight:0,
    taskDetail:{},
    titleValue:"",
    contentValue:"",
    repeatTypes:[
      {
        value:0,
        label:"一次性"
      },
      {
        value:1,
        label:"每天"
      },
      {
        value:2,
        label:"每周"
      },
      {
        value:3,
        label:"每月"
      },
    ],
    WeeksList:[
      {
        value:2,
        label:"星期一"
      },
      {
        value:3,
        label:"星期二"
      },
      {
        value:4,
        label:"星期三"
      },
      {
        value:5,
        label:"星期四"
      },
      {
        value:6,
        label:"星期五"
      },
      {
        value:7,
        label:"星期六"
      },
      {
        value:1,
        label:"星期天"
      },
    ],
    id:null,
    DaysList:[],
    chargePerson:[],
    chargePersonNames:"",
    inspectPerson:[],
    inspectPersonNames:"",
    dayValue:0,
    showDayValue:1,
    weekValue:0,
    firstRepeat:0,
    oneRepeatTime:"",
    oneRepeatDate:"",
    isUse:1,
    usersList:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
   this.getNowTime();
   var DaysList=[];
      for (let index = 1; index < 32; index++) {
        DaysList.push(index);
      }
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('showDetail', function(res) {
      var data=res.data
      console.log(data,"====>task-detail")
      if(data){
        that.CronToMessage(data.cron)
        // var personNameList=that.updateShowPersons(data.chargePersonId,data.inspectPersonId)
        var chargePerson=that.transformArray(data.chargePersonId)
        var inspectPerson=that.transformArray(data.inspectPersonId)
        console.log(chargePerson)
        console.log(inspectPerson)
        that.setData({
          id:data.id,
          titleValue:data.title,
          contentValue:data.content,
          chargePerson:chargePerson,
          inspectPerson:inspectPerson,
          isUse:data.isUse,
          chargePersonNames:data.chargePersonName,
          inspectPersonNames:data.inspectPersonName,
        })
      }
      that.setData({
        taskDetail:data,
      })
    })
    that.setData({
      scrollHeight: app.getScrollHeight(45),
      DaysList:DaysList
    })
  },
  //转换成数组
  transformArray(data){
    var dataArray=[]
    if(!data){
      return dataArray
    }
    else if(data.indexOf(",")!=-1){
      dataArray=data.split(",")
    }
    else{
      dataArray.push(data)
    }
    return dataArray
  },
  updateShowPersons(personIds,checkids){
    var that=this;
    var personList=[]
    var personNames=""
    var checkPersons=""
    lbbService.getAllInnerUser({}, res => {
      var usersList=res.data
      var idsList=that.transformArray(personIds)
      for (let index = 0; index < idsList.length; index++) {
      for (let j = 0; j < usersList.length; j++) {
          if(usersList[j].uid==idsList[index]){
            if(idsList.length-1==index){
              personNames=personNames+usersList[j].userName
            }
            else {
              personNames=personNames+usersList[j].userName+","
            }
          }
        }
      
      }
      var checkidsList=that.transformArray(checkids)
      for (let index = 0; index < checkidsList.length; index++) {
        for (let j = 0; j < usersList.length; j++) {
            if(usersList[j].uid==checkidsList[index]){
              if(checkidsList.length-1==index){
                checkPersons=checkPersons+usersList[j].userName
              }
              else {
                checkPersons=checkPersons+usersList[j].userName+","
              }
            }
          }
        
        }
        personList.push(personNames)
        personList.push(checkPersons)
      return personList
  })
  },
  getNowTime(){
    var that=this;
    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //获取年份  
    var Y =date.getFullYear();
    //获取月份  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var hour = date.getHours()
    var minute = date.getMinutes()
    if(minute<10){
      minute="0"+minute
    }
    this.setData({
      oneRepeatDate:Y+"-"+M+"-"+D,
      oneRepeatTime:hour+":"+minute
    })
  },
  firstPickerBindChange:function(e){
    var index=e.detail.value[0];
    var beChoose=this.data.repeatTypes[index].value;
    if(beChoose==0){
      this.getNowTime()
    }
    if(beChoose==3){
      var DaysList=[];
      for (let index = 1; index < 32; index++) {
        DaysList.push(index);
      }
      this.setData({
        DaysList:DaysList
      })
    }
    this.setData({
      firstRepeat:beChoose
    })
  },
  bindDateChange:function(e){
    var value=e.detail.value
    this.setData({
      oneRepeatDate:value
    })
  },
  bindTimeChange:function(e){
    var value=e.detail.value
    this.setData({
      oneRepeatTime:value
    })
  },
  bindWeekChange:function(e){
    var value=e.detail.value
    this.setData({
      weekValue:value
    })
  },
  bindDaysChange:function(e){
    var value=e.detail.value
    console.log(value)
    this.setData({
      dayValue: value,
      showDayValue:(parseInt(value)+1)+""
    })
  },
  bindTitleInput: function (e) {
    this.setData({
      titleValue: e.detail.value
    })
  },
  showPersonPage:function(e){
    var that=this
    let type = e.currentTarget.dataset.type
    var chargePerson=this.data.chargePerson
    var inspectPerson=this.data.inspectPerson
    var detail=[]
    if(type==0){
      detail= chargePerson
    }
    else{
      detail=inspectPerson
    }
    wx.navigateTo({
      url: '/pages/personChoose/personChoose',
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('getPersonType', { data: type,
            detail: detail})
      
      },
      events: {
        backFn: (backParams) => {
          var type=backParams[0]
          var person=backParams[1]
          var personIds=[]
          for (let index = 0; index < person.length; index++) {
            personIds.push(person[index].uid)
          }
          var personName=backParams[2]
          if(type==0){
            that.setData({
              chargePerson:personIds,
              chargePersonNames:personName
            })
          }
          else{
            that.setData({
              inspectPerson:personIds,
              inspectPersonNames:personName
            })
          }
          
        }
      }
    })
  },
  bindContentAreaBlur: function(e) {
    this.setData({
      contentValue: e.detail.value
    })
  },
  switch1Change:function(e){
    console.log(e.detail.value)
    if(e.detail.value){
      this.setData({
        isUse: 1
      })
    }
    else{
      this.setData({
        isUse: 0
      })
    }
  },
  finishChange:function(){
    var id=this.data.id
    var title=this.data.titleValue
    var content=this.data.contentValue
    var chargePerson=this.data.chargePerson
    var inspectPerson=this.data.inspectPerson
    var dayValue=this.data.showDayValue
    var weekValue=this.data.weekValue
    var firstRepeat=this.data.firstRepeat
    var oneRepeatTime=this.data.oneRepeatTime
    var oneRepeatDate=this.data.oneRepeatDate
    var isUse=this.data.isUse
    var cron =this.MessageToCron(firstRepeat,oneRepeatDate,oneRepeatTime,weekValue,dayValue);
    var chargePersonId=chargePerson.toString()
    var inspectPersonId=inspectPerson.toString()
    console.log(cron)
    if(id){
      lbbService.updateTask({id,title,content,cron,chargePersonId,inspectPersonId,isUse},res=>{
        wx.navigateBack({
          delta: 1,
        })
      })
    }
    else{
      lbbService.insertTask({title,content,cron,chargePersonId,inspectPersonId,isUse},res=>{
        wx.navigateBack({
          delta: 1,
        })
      })
    }
    
  },
  //数据转cron表达式
  MessageToCron:function(firstRepeat,oneRepeatDate,oneRepeatTime,weekValue,dayValue){
    var cron=""
    //一次性
    if(firstRepeat==0){
     var dateList=oneRepeatDate.split("-")
     var timeList=oneRepeatTime.split(":")
     cron="0 "+timeList[1]+" "+timeList[0]+" "+dateList[2]+" "+dateList[1]+" "+"? "+dateList[0]
    }
    //每天
    else if(firstRepeat==1){
      var dateList=oneRepeatDate.split("-")
      var timeList=oneRepeatTime.split(":")
      cron="0 "+timeList[1]+" "+timeList[0]+" * * ?"
    }
    //每周
    else if(firstRepeat==2){
      var weeks=1;
      if(weekValue==6){
        weeks==1
      }
      else{
        weeks=parseInt(weekValue)+2
      }
      cron="0 0 0 ? * "+weeks
    }
    //每月
    else if(firstRepeat==3){
     var timeList=oneRepeatTime.split(":")
     cron="0 "+timeList[1]+" "+timeList[0]+" "+dayValue+" * ?"
    }
    return cron;
  },

  // cron转数据
  CronToMessage:function(cron){
    var crons=cron.split(" ");
    var min=crons[1];
    var hour=crons[2];
    var day=crons[3];
    var month=crons[4];
    var week=crons[5];
    var year=crons[6];
    if(year){
      this.setData({
        firstRepeat:0,
        oneRepeatDate:year+"-"+month+"-"+day,
        oneRepeatTime:hour+":"+min
      })
    }
    else if(day=='*'){
      this.setData({
        firstRepeat:1,
        oneRepeatTime:hour+":"+min
      })
    }
    else if(week>0&&week<8){
      var weekValue=0;
      if(week==1){
        weekValue==7
      }
      else{
        weekValue=week-2
      }
      this.setData({
        firstRepeat:2,
        weekValue:weekValue
      })
    }
    else if(month=='*'&&!year){
      this.setData({
        firstRepeat:3,
        dayValue:parseInt(day)-1,
        showDayValue:day,
        oneRepeatTime:hour+":"+min
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})